package com.adinnet.admin.teacher.controller;


import com.adinnet.admin.classs.model.Classs;
import com.adinnet.admin.classs.service.ClasssService;
import com.adinnet.admin.common.service.CommonService;
import com.adinnet.admin.organization.service.OrganizationService;
import com.adinnet.admin.school.service.SchoolService;
import com.adinnet.admin.system.model.SysUser;
import com.adinnet.admin.system.model.vo.SysUserInfo;
import com.adinnet.admin.teacher.model.Teacher;
import com.adinnet.admin.teacher.model.form.TeacherForm;
import com.adinnet.admin.teacher.model.vo.TeacherReq;
import com.adinnet.admin.teacher.model.vo.TeacherResp;
import com.adinnet.admin.teacher.service.TeacherService;
import com.adinnet.admin.user.model.User;
import com.adinnet.admin.user.service.UserService;
import com.adinnet.common.upload.UploadUtils;
import com.adinnet.core.JsonResult;
import com.adinnet.core.PageResult;
import com.adinnet.core.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 教师表 前端控制器
 * </p>
 *
 * @author chenjia
 * @since 2021-06-09
 */
@RestController
@RequestMapping("admin/teacher")
public class TeacherController {

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private ClasssService classsService;

    @Autowired
    private UserService userService;


    /**
     * 教师页面
     * 1，返回用户可查询的机构列表
     * 2，返回用户可查询的校区列表
     * 3，返回用户可查询的班级列表
     * @param model
     * @return
     */
    @GetMapping()
    public ModelAndView teacher(Model model){
        SysUserInfo sysUserInfo=commonService.getLoginUser();
        model.addAttribute("organizationsList", organizationService.getListByUserRole(sysUserInfo));
        model.addAttribute("schoolList", schoolService.getListByUserRole(sysUserInfo));
        model.addAttribute("classsList", classsService.getListByUserRole(sysUserInfo));
        return new ModelAndView("teacher/teacher.html");
    }


    /**
     * 教师列表
     * 默认页面
     * 1，超级管理员查所有
     * 2，机构查机构下的数据
     * 3，校区查校区的数据
     * 4，班级查班级的数据
     * @param teacherForm
     * @return
     */
    @GetMapping("/teacherList")
    public PageResult<TeacherResp> list(TeacherForm teacherForm) {
        SysUserInfo sysUser= commonService.getLoginUser();
        //默认页面处理和重置搜索的处理
        if(teacherForm.getClassId()==null&&teacherForm.getOrganizationId()==null&&teacherForm.getSchoolId()==null){
            if(sysUser!=null){
                switch (sysUser.getMaxRole()){
                    case "admin":
                        break;
                    case "organization":
                        teacherForm.setOrganizationId(sysUser.getOrganizationId());
                        break;
                    case "school":
                        teacherForm.setSchoolId(sysUser.getSchoolId());
                        break;
                    case "classs":
                        teacherForm.setSysUserId(sysUser.getId());
                        break;
                    default:
                        break;
                }
            }
        }
        return teacherService.queryTeacherList(teacherForm);
    }

    /**
     * 新增教师
     **/
    @ResponseBody
    @RequestMapping("add")
    public JsonResult add(TeacherReq teacherReq, HttpServletRequest request) {
        try{
            User u=userService.getOne(new QueryWrapper<User>().eq("tel_no",teacherReq.getTelNo()).eq("deleted", 0));
            if(u!=null){
                return JsonResult.error("添加失败,手机号已存在注册用户");
            }
            Integer teacherId=teacherService.addNewTeacher(teacherReq);
            if(teacherId!=null&&teacherId.intValue()>0){
                commonService.saveOperation(request,"教师列表-新增教师,新增教师id为："+teacherId);
                return JsonResult.ok("添加成功");
            }else {
                return JsonResult.error("添加失败");
            }
        }catch (BizException e){
            return JsonResult.error("注册失败,发送短信失败");
        }
    }

    /**
     * 编辑教师
     **/
    @ResponseBody
    @RequestMapping("update")
    public JsonResult update(TeacherReq teacherReq, HttpServletRequest request) {
        try{
            Integer teacherId=teacherService.editTeacher(teacherReq);
            if(teacherId!=null&&teacherId.intValue()>0){
                commonService.saveOperation(request,"教师列表-编辑教师,编辑的教师id为："+teacherId);
                return JsonResult.ok("编辑成功");
            }else {
                return JsonResult.error("编辑失败");
            }
        }catch (BizException e){
            return JsonResult.error("编辑失败,发送短信失败");
        }
    }


    /**
     * 修改教师账号状态
     **/
    @ResponseBody
    @RequestMapping("updateState")
    public JsonResult updateState(Integer teacherId, Integer state, HttpServletRequest request) {
        if (teacherId == null) {
            return JsonResult.error("参数teacherId不能为空");
        }
        if (state == null || (state != 0 && state != 1)) {
            return JsonResult.error("状态值不正确");
        }
        Teacher teacher = teacherService.getById(teacherId);
        User user = new User();
        user.setId(teacher.getUserId());
        user.setStatus(state);
        if (userService.updateById(user)) {
            commonService.saveOperation(request,"教师列表-修改教师账号状态,修改的教师为："+teacherId);
            return JsonResult.ok();
        } else {
            return JsonResult.error();
        }
    }


    /**
     * 批量删除儿童
     */
    @RequestMapping("deleteIds")
    @ResponseBody
    public JsonResult deleteIds(String teacherIds, HttpServletRequest request) {
        commonService.saveOperation(request,"教师列表-删除教师：删除的教师id为："+teacherIds);
        return teacherService.deleteIds(teacherIds);
    }

    /**
     * 导入教师账号
     * @param file
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/importTeacher")
    @Transactional(rollbackFor = Exception.class)
    public JsonResult importTeacher(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request) throws Exception {
        //获取导入人的权限
        SysUser sysUser= commonService.getLoginUser();
        Integer organizationId=null;
        Integer schoolId=null;
        Integer sysUserId=null;
        //根据登陆人权限判断
        if(sysUser!=null){
            switch (((SysUserInfo) sysUser).getMaxRole()){
                case "admin":
                    break;
                case "organization":
                    organizationId=sysUser.getOrganizationId();
                    break;
                case "school":
                    schoolId=sysUser.getSchoolId();
                    break;
                case "classs":
                    sysUserId=sysUser.getId();
                    break;
                default:
                    break;
            }
        }

        List<Teacher> teacherList = new ArrayList<>();
        List<List<String>> list = UploadUtils.excelToList(file);
        List<String> failList = new ArrayList<>();
        list.remove(0);
        for (List<String> ls : list) {
            if(!StringUtils.isNotEmpty(ls.get(0)))throw new BizException("所有导入失败，有学生姓名为空,请检查后重试");
            if(StringUtils.isBlank(ls.get(2))||!StringUtils.isNumeric(ls.get(2)))throw new BizException("所有导入失败，有学生性别为空或格式错误,请检查后重试");
            if(!StringUtils.isNotEmpty(ls.get(3)))throw new BizException("所有导入失败，有所属校区为空,请检查后重试");
            if(!StringUtils.isNotEmpty(ls.get(4)))throw new BizException("所有导入失败，有所属班级为空,请检查后重试");
            if(!StringUtils.isNotEmpty(ls.get(5)))throw new BizException("所有导入失败，有学生手机号为空,请检查后重试");
            Teacher teacher = new Teacher();
            if(StringUtils.isNotEmpty(ls.get(1))){
                teacher.setEnglishName(ls.get(1));
            }
            teacher.setChildName(ls.get(0));
            teacher.setSex(Integer.valueOf(ls.get(2)));
            User u=userService.getOne(new QueryWrapper<User>().eq("tel_no",ls.get(5)).eq("deleted", 0));
            if(u!=null){
                failList.add(ls.get(5));
                continue;
            }
            Classs classs=classsService.selectClasssForExcel(ls.get(3),ls.get(4),organizationId,schoolId,sysUserId);
            if(classs==null){
                failList.add(ls.get(5));
                continue;
            }
            TeacherReq teacherReq = new TeacherReq();
            teacherReq.setChildName(ls.get(0));
            if(StringUtils.isNotEmpty(ls.get(1))){
                teacherReq.setEnglishName(ls.get(1));
            }
            teacherReq.setSex(Integer.valueOf(ls.get(2)));
            teacherReq.setSchoolId(classs.getSchoolId());
            teacherReq.setClassId(classs.getId());
            teacherReq.setTelNo(ls.get(5));
            Integer teacherId=teacherService.addNewTeacher(teacherReq);
            if(teacherId!=null&&teacherId.intValue()>0){
                teacherList.add(teacher);
            }else {
                failList.add(ls.get(5));
            }
        }
        if(!teacherList.isEmpty()){
            commonService.saveOperation(request,"教师列表-导入教师,导入成功的条数为："+teacherList.size());
        }
        return JsonResult.ok(failList.size()+"条数据导入失败！");
    }

}
